// feedback.js
import { upLoadImage } from '../../hooks/upLoadFile'
import {submitSuggest} from "../../api/move"
Page({
  data: {
    categoryList: ['功能问题', '操作问题', '性能问题', '其他'] as Array<string>,  // 问题类别列表
    selectedCategory: 0 as number, // 默认选择第一个类别
    description: '' as string, // 反馈内容
    hasSelectedImages: false as boolean, // 是否有已选择的图片
    selectedImagePath: [] as MediaFile[], // 已选择图片的本地路径
    feedbackStatusClass: '' as string, // 提交状态类名
    feedbackStatusText: '' as string, // 提交状态文字
    contact:"" as string,
    timer: null as number | null,
  },

  handleInput(e: any): void {
    this.setData({ description: e.detail.value });
  },

  onChangeCategory(e: any): void {
    this.setData({ selectedCategory: e.detail.value });
  },

  // 上传截图
  chooseImage(): void {
    const that = this
    // 选择图片的逻辑，获取临时文件路径后更新selectedImagePath数据
    wx.chooseMedia({
      count: 3, // 默认9，最多可选9张，这里设置为1张
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        if (that.data.selectedImagePath.length + res.tempFiles.length <= 3) {
          that.setData({
            hasSelectedImages: true,
            selectedImagePath: [...res.tempFiles, ...that.data.selectedImagePath].slice(0, 3) // 只保留前3个元素
          });
        } else {
          wx.showToast({
            title: '您已达到最多选择3张图片的数量限制',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.error('chooseImage failed', err);
      }
    });
  },

  onContactInput(e: any) {
    this.setData({ contact: e.detail.value });
  },
  // 点击提交反馈
  async onSubmitFeedback(e: any): Promise<void> {
    const formData = e.detail.value;
    formData.category = this.data.categoryList[this.data.selectedCategory];
    const uploadPromises: Promise<string | null>[] = [];
    // 上传
    for (let i = 0; i < this.data.selectedImagePath.length; i++) {
      uploadPromises.push(upLoadImage(this.data.selectedImagePath[i].tempFilePath));
    }
    // 图片全部上传完成
    try {
      const results = await Promise.all(uploadPromises);
      console.log(results, this.data.selectedImagePath,"this.data.selectedImagePath");
      // 图片全部上传完成
      if (results.length === this.data.selectedImagePath.length && results.every(item =>{ return item})) {
        formData.imageURL = results;
        // 在这里发送带有图片URL的请求
        const res = await submitSuggest(formData);

        if (!res.code) {
          this.setData({
            feedbackStatusClass: 'success',
            feedbackStatusText: '感谢您的反馈，我们会尽快处理！',
            selectedImagePath:[],
            selectedCategory:0,
          });
          this.data.timer = setTimeout(() => {
            wx.navigateBack()
          },1000);
        } else {
          this.setData({
            feedbackStatusClass: 'error',
            feedbackStatusText: '反馈提交失败，请稍后再试！',
          });
        }
      }
    } catch (error) {
      console.error('反馈提交失败，请稍后再试', error);
    }
  },
  // 点击x删除图片
  onDeleteImage(e: any): void {
    const index = e.currentTarget.dataset.index;
    const newImagesList = [...this.data.selectedImagePath];
    newImagesList.splice(index, 1);
    this.setData({
      selectedImagePath: newImagesList,
    });
  },
  onUnload() {
    this.data.timer = null
  }
});